<template>
    <div class="antd_layout">
        <!-- 左侧边栏 -->
        <div class="layout_sider">
            <div class="sider_opertors">
                <a-button size="small" type="primary">新增</a-button>
                <a-button size="small" type="primary">修改</a-button>
                <a-button size="small" type="primary">删除</a-button>
                <a-button size="small" type="primary">展开</a-button>
            </div>
            <!-- 文件树 -->
            <div style="margin-top: 15px">
                <DataTree />
            </div>
        </div>

        <!-- 主体 -->
        <div class="layout_content">
            <!-- 顶部按钮 -->
            <div class="content_opertors">
                <a-button type="primary" @click="searchTableData">查询</a-button>
                <a-button type="primary" @click="changeVisible">导入</a-button>
                <a-button type="primary">汇总报表生成</a-button>
            </div>

            <div class="content_main">
                <!-- 自定义筛选区 -->
                <div class="search_form">
                    <SearchForm ref="temSearchForm" :columnsNum="columnsNum" :isShowSearchBtns="isShowSearchBtns" :formdata="formdata" :formItems="formItems">
                        <template #customFormBtns>
                            <a-button type="primary" html-type="submit">Submit</a-button>
                        </template>
                    </SearchForm>
                </div>
                <div class="content_table">
                    <!-- 表格区域 -->
                    <div id="luckysheet_main" style="margin: 0px; padding: 0px"></div>
                    <!-- 文件属性+表格行属性区域 -->
                    <DescCard :descInfo="descInfo" :isDisabled="true" />
                </div>
            </div>
        </div>
        <!-- 导入模态框 -->
        <ImportModal
            :visible="visible"
            :sheetTplInfo="sheetTplInfo"
            :allTplInfo="allTplInfo"
            :tenRowData="tenRowData"
            :allRowData="allRowData"
            @changeIsvisible="changeIsvisible"
            @changeVisible="changeVisible"
            @fileBeforeUpload="fileBeforeUpload"
            @newOpen="newOpen"
            @addTpl="addTpl"
        />
        <!-- 抽屉预览页面 -->
        <DrawerPreview :isvisible="isvisible" @changeIsvisible="changeIsvisible" :drawerFile="drawerFile" :allRowData="allRowData" />
        <!-- 隐藏的luckysheet容器，供luckyexcel转换数据格式使用 -->
        <div id="luckysheet_for_trans_data" style="visibility: hidden"></div>
    </div>
</template>

<script>
import dayjs from 'dayjs';
import LuckyExcel from 'luckyexcel';

import DataTree from './Component/DataTree.vue';
import DescCard from '../../components/CustomCard/DescCard.vue';
import SearchForm from '@/components/CustomSearch/searchForm.vue';
import ImportModal from './Component/ImportModal.vue';
import DrawerPreview from './Component/DrawerPreview.vue';

import { toSheetsTable } from '@/util/luckysheetToTable';

import { useTplInfoStore } from '@/store';

import { guessTemplate, createTemplate } from '@/request/api/dataSourceAPI';

import { message } from 'ant-design-vue';

export default {
    components: {
        DataTree,
        DescCard,
        SearchForm,
        ImportModal,
        DrawerPreview,
    },
    data() {
        return {
            // 导入弹窗是否可见
            visible: false,
            // 抽屉是否可见
            isvisible: false,
            // 属性面板数据
            descInfo: [
                {
                    title: '属性',
                    items: [
                        {
                            name: '区划：',
                            key: 'division',
                            value: '304822',
                        },
                        {
                            name: '年度：',
                            key: 'years',
                            value: '2022',
                        },
                        {
                            name: '报表日期(起)：',
                            key: 'start_time',
                            value: '2022-09-04',
                        },
                        {
                            name: '报表日期(止)：',
                            key: 'end_time',
                            value: '2022-09-04',
                        },
                    ],
                },
                {
                    title: '行属性',
                    items: [
                        {
                            name: '科目(行)：',
                            key: 'sub',
                            value: '',
                        },
                    ],
                },
            ],
            // 查询表单一行放3个表单
            columnsNum: 3,
            // 查询表单是否显示按钮
            isShowSearchBtns: false,
            // 查询表单默认值
            formdata: {
                str: 'aaa',
                sex: '1',
                fruit: ['pear'],
                date: dayjs(),
                xialashu1: 'parent 1-0',
                xialashu2: ['leaf1', 'parent 1-1'],
            },
            // 查询表单动态生成表单的数据
            formItems: [
                // Input输入框
                {
                    name: 'str',
                    label: 'Input输入框：',
                    rules: [],
                    itemInfo: {
                        type: 'Input',
                        events: {
                            // 支持组件的事件
                            // change(value){
                            //   console.log(value)
                            // },
                            input(value) {
                                console.log(value);
                            },
                        },
                    },
                },
                // Select单选下拉框
                {
                    name: 'sex',
                    label: 'Select单选下拉框：',
                    rules: [],
                    itemInfo: {
                        type: 'Select',
                        mode: '', //单选
                        filterOption: (input, option) => {
                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                        },
                        events: {
                            // 支持组件的事件
                            // change(value){
                            //   console.log(value)
                            // },
                        },
                        options: [
                            {
                                value: '0',
                                label: '女',
                            },
                            {
                                value: '1',
                                label: '男',
                            },
                        ],
                    },
                },
                // Select多选下拉框
                {
                    name: 'fruit',
                    label: 'Select多选下拉框：',
                    rules: [],
                    itemInfo: {
                        type: 'Select',
                        mode: 'multiple', //多选
                        filterOption: (input, option) => {
                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                        },
                        events: {
                            // 支持组件的事件
                            // change(value){
                            //   console.log(value)
                            // },
                        },
                        options: [
                            {
                                value: 'apple',
                                label: '苹果',
                            },
                            {
                                value: 'orange',
                                label: '桔子',
                            },
                            {
                                value: 'pear',
                                label: '梨子',
                            },
                        ],
                    },
                },
                // Datebox日期框
                {
                    name: 'date',
                    label: 'Datebox日期框：',
                    rules: [],
                    itemInfo: {
                        type: 'Datebox',
                    },
                },
                // SelectTreeOne单选下拉树
                {
                    name: 'xialashu1',
                    label: 'SelectTreeOne单选下拉树：',
                    rules: [],
                    itemInfo: {
                        type: 'SelectTreeOne',
                        mode: '', //单选
                        filterTreeNode: (input, treeNode) => {
                            return treeNode.title.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                        },
                        events: {
                            // 支持组件的事件
                            // change(value){
                            //   console.log(value)
                            // },
                        },
                        treeData: [
                            {
                                title: 'parent 1',
                                value: 'parent 1',
                                children: [
                                    {
                                        title: 'parent 1-0',
                                        value: 'parent 1-0',
                                        children: [
                                            {
                                                title: 'my leaf',
                                                value: 'leaf1',
                                            },
                                            {
                                                title: 'your leaf',
                                                value: 'leaf2',
                                            },
                                        ],
                                    },
                                    {
                                        title: 'parent 1-1',
                                        value: 'parent 1-1',
                                    },
                                ],
                            },
                        ],
                    },
                },
                // SelectTreeMul多选下拉树
                {
                    name: 'xialashu2',
                    label: 'SelectTreeMul多选下拉树：',
                    rules: [],
                    itemInfo: {
                        type: 'SelectTreeMul',
                        mode: 'multiple', //多选
                        filterTreeNode: (input, treeNode) => {
                            return treeNode.title.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                        },
                        events: {
                            // 支持组件的事件
                            // change(value){
                            //   console.log(value)
                            // },
                        },
                        treeData: [
                            {
                                title: 'parent 1',
                                value: 'parent 1',
                                children: [
                                    {
                                        title: 'parent 1-0',
                                        value: 'parent 1-0',
                                        children: [
                                            {
                                                title: 'my leaf',
                                                value: 'leaf1',
                                            },
                                            {
                                                title: 'your leaf',
                                                value: 'leaf2',
                                            },
                                        ],
                                    },
                                    {
                                        title: 'parent 1-1',
                                        value: 'parent 1-1',
                                    },
                                ],
                            },
                        ],
                    },
                },
            ],
            // 单个sheet页的模板匹配信息
            sheetTplInfo: [],
            // 更多模板，后端存储的模板
            allTplInfo: [],
            // 抽屉luckysheet表格展示的数据
            drawerFile: {},
            // 选择文件按钮、新增模板按钮传给接口的数据
            tenRowData: [],
            // 导入按钮传给接口的文件数据
            allRowData: [],
        };
    },
    beforeMount() {},
    mounted() {
        console.log(useTplInfoStore());
        this.init();
    },
    methods: {
        //查询按钮
        searchTableData() {
            const filterData = this.getdata();
            console.log(filterData);
            //拿数据查询表格数据
        },
        // 导入弹窗，取消按钮触发的事件
        newOpen() {
            this.sheetTplInfo = [];
        },
        // 控制导入弹窗显示隐藏
        changeVisible() {
            this.visible = !this.visible;
        },
        // 控制抽屉页显示隐藏
        changeIsvisible() {
            this.isvisible = !this.isvisible;
        },
        // 拿取自定义筛选条件的信息
        getdata() {
            let formData = this.$refs.temSearchForm.getFormData();
            console.log(formData);
            return JSON.parse(JSON.stringify(formData));
        },
        // 初始化首页表格
        init() {
            var options = {
                container: 'luckysheet_main', //luckysheet为容器id
                lang: 'zh',
                gridKey: '1',
                allowEdit: false, // 是否允许前台编辑
                showtoolbar: false, // 是否显示工具栏
                showinfobar: false, // 是否显示顶部信息栏
                sheetFormulaBar: false, // 是否显示公式栏
                showsheetbarConfig: {
                    add: false, //新增sheet
                    menu: false, //sheet管理菜单
                    sheet: true, //sheet页显示
                },
                sheetRightClickConfig: {
                    delete: false, // 删除
                    copy: false, // 复制
                    rename: false, //重命名
                    color: false, //更改颜色
                    hide: false, //隐藏，取消隐藏
                    move: false, //向左移，向右移
                },
                // pager: {
                //     pageIndex: 1, //当前的页码
                //     pageSize: 10, //每页显示多少行数据
                //     total: 50, //数据总行数
                //     selectOption: [10, 20] //允许设置每页行数的选项
                // },
                hook: {
                    rangeSelect: function (sheet, range) {
                        // console.log(sheet)
                        // console.log(range)
                    },
                    sheetActivate: function (index, isPivotInitial, isNewSheet) {
                        // luckysheet.setSheetActive(1) // 手动激活指定sheet页
                        // luckysheet.getSheet(index).name
                        console.info(index, isPivotInitial, isNewSheet);
                    },
                },
                data: [
                    {
                        name: 'Cell', //工作表名称
                        color: '', //工作表颜色
                        index: 0, //工作表索引
                        status: 1, //激活状态
                        order: 0, //工作表的下标
                        hide: 0, //是否隐藏
                        row: 36, //行数
                        column: 18, //列数
                        defaultRowHeight: 19, //自定义行高
                        defaultColWidth: 73, //自定义列宽
                        celldata: [
                            {
                                r: 0,
                                c: 0,
                                v: {
                                    ct: { fa: 'General', t: 'g' },
                                    m: 'value1',
                                    v: 'value1',
                                },
                            },
                            {
                                r: 0,
                                c: 1,
                                v: {
                                    ct: { fa: 'General', t: 'g' },
                                    m: 'value2',
                                    v: 'value2',
                                },
                            },
                        ], //初始化使用的单元格数据
                        config: {
                            merge: {}, //合并单元格
                            rowlen: {}, //表格行高
                            columnlen: {}, //表格列宽
                            rowhidden: {}, //隐藏行
                            colhidden: {}, //隐藏列
                            borderInfo: {}, //边框
                            authority: {}, //工作表保护
                        },
                        scrollLeft: 0, //左右滚动条位置
                        scrollTop: 0, //上下滚动条位置
                        luckysheet_select_save: [], //选中的区域
                        calcChain: [], //公式链
                        isPivotTable: false, //是否数据透视表
                        pivotTable: {}, //数据透视表设置
                        filter_select: {}, //筛选范围
                        filter: null, //筛选配置
                        luckysheet_alternateformat_save: [], //交替颜色
                        luckysheet_alternateformat_save_modelCustom: [], //自定义交替颜色
                        luckysheet_conditionformat_save: {}, //条件格式
                        frozen: {}, //冻结行列配置
                        chart: [], //图表配置
                        zoomRatio: 1, // 缩放比例
                        image: [], //图片
                        showGridLines: 1, //是否显示网格线
                        dataVerification: {}, //数据验证配置
                    },
                    {
                        name: 'Sheet2',
                        color: '',
                        index: 1,
                        status: 0,
                        order: 1,
                        celldata: [],
                        config: {},
                    },
                    {
                        name: 'Sheet3',
                        color: '',
                        index: 2,
                        status: 0,
                        order: 2,
                        celldata: [],
                        config: {},
                    },
                ],
            };
            luckysheet.destroy();
            luckysheet.create(options);
        },
        // 导入弹窗，选择文件按钮触发的事件
        fileBeforeUpload(file) {
            let currInstance = this;
            LuckyExcel.transformExcelToLucky(file, (exportJson, luckysheetfile) => {
                if (exportJson.sheets == null || exportJson.sheets.length == 0) {
                    alert('Failed to read the content of the excel file, currently does not support xls files!');
                    return;
                }
                // console.log(luckysheetfile,'luckysheetfile------------')
                luckysheet.destroy();
                luckysheet.create({
                    container: 'luckysheet_for_trans_data',
                    showinfobar: false, // 是否显示顶部信息栏
                    gridKey: '34567',
                    data: exportJson.sheets,
                    hook: {
                        workbookCreateAfter: function () {
                            currInstance.drawerFile = exportJson.sheets;
                            console.log('------------exportJson', exportJson);
                            currInstance.sheetTplInfo = [];
                            exportJson.sheets.forEach((item, index) => {
                                currInstance.sheetTplInfo.push({
                                    name: item.name,
                                    key: index,
                                });
                            });
                            // console.log(toSheetsTable(exportJson.sheets,2,10));
                            currInstance.allRowData = toSheetsTable(exportJson.sheets, exportJson.info.name, 1);
                            currInstance.tenRowData = toSheetsTable(exportJson.sheets, exportJson.info.name, 2, 10);
                            // 发送前10条数据，请求模板匹配信息
                            guessTemplate(currInstance.tenRowData).then((res) => {
                                if (res.state == '200') {
                                    const { hotData, data } = res;
                                    currInstance.sheetTplInfo = [];
                                    currInstance.allTplInfo = [];
                                    hotData.forEach((item, index) => {
                                        currInstance.sheetTplInfo.push({
                                            name: item.name,
                                            key: item.index || index,
                                            options: item.template.map((curOption) => {
                                                curOption.key = item.index || index;
                                                return curOption;
                                            }),
                                        });
                                    });
                                    currInstance.allTplInfo = data;
                                    message.success(res.msg || '模板匹配信息获取成功！');
                                } else {
                                    message.error(res.msg || '模板匹配信息获取失败！');
                                }
                            });
                        },
                    },
                });
            });
        },
        // 导入弹窗，新增模板按钮触发的事件
        addTpl() {
            let currInstance = this;
            const TplInfoStore = useTplInfoStore();
            // TplInfoStore.sethotData([1, 2].map((s, i) => (
            //     {
            //         index: i,
            //         name: 'sheet0',
            //         properties: ['区划：', '报表日期（起）：', '报表日期（止）：', '金额单位：'].map((item, index) => {
            //             return {
            //                 id: index,
            //                 name: item,
            //                 value: item,
            //                 typeCode: `input${index}`
            //             }
            //         }),
            //         template: {
            //             autoAnalysis: 1, // 1:true 0:false
            //             code: '',
            //             id: 1,
            //             name: 'sanmu',
            //             startLine: Number((Math.random() * 10).toFixed(0)),
            //             suitability: 0,
            //             importColumns: ['A', 'B', 'C', 'D', 'E', 'F'].map((cur, itemIndex) => ({
            //                 columnCode: cur,
            //                 columnDataType: (Math.random()) * 10 > 5 ? 's' : 'n',
            //                 columnName: `${cur}${Math.random().toFixed(0)}`,
            //                 columnType: (Math.random()) * 10 > 5 ? 1 : 2,
            //             }))
            //         }
            //     })))
            // currInstance.changeIsvisible()
            // console.log(TplInfoStore)
            // return

            // 传入10行数据，请求模板详细信息
            createTemplate(this.tenRowData).then((res) => {
                // debugger
                // 打开抽屉页
                if (res.state == '200') {
                    TplInfoStore.sethotData(res.hotData);
                    message.success(res.msg || '模板分析成功，请检查修改并保存！');
                    currInstance.changeIsvisible();
                } else {
                    message.error(res.msg || '模板分析失败！');
                }
            });
        },
    },
};
</script>

<style lang="less">
.antd_layout {
    display: flex;
    justify-content: space-between;
    height: 100%;
    width: 100%;
}

.layout_sider {
    display: inline-block;
    padding: 20px;
    height: 100%;
    width: 20%;
    border: 2px solid #f6f6f6;

    .sider_opertors {
        display: flex;
        justify-content: space-between;
    }
}

.layout_content {
    display: inline-block;
    flex: 1;
    padding: 20px;
    height: 100%;
    border: 2px solid #f6f6f6;

    .content_opertors {
        height: 32px;

        .ant-btn {
            margin-right: 16px;
        }
    }
}

.content_main {
    margin-top: 15px;
    height: calc(100% - 47px);
}

.search_form {
    max-height: 112px;
}

.content_table {
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: calc(100% - 112px);

    .ant-table-wrapper,
    #luckysheet_main {
        flex: 1;
        height: 100%;
    }

    .ant-card {
        width: 26%;
        :deep(.ant-card-head) {
            border: none !important;
        }
    }
}

.ant-drawer {
    z-index: 1200;
}

.luckysheet-cols-menu {
    position: absolute;
    left: 300px !important;
    bottom: 76px !important;
}

.ant-modal-mask {
    z-index: 1003;
}

.ant-modal-wrap {
    z-index: 1004;
}

.ant-message {
    z-index: 1222 !important;
}
</style>
